//
//  AppDelegate+NotificationCenter.m
//  CreditManger
//
//  Created by chaiyanan on 15/11/5.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "AppDelegate+NotificationCenter.h"
#import "HBLoginManager.h"
#import "HBSetPushAccountManager.h"
#import "BPush.h"

#import "HBCheckVersionInfo.h"
#import "HBCheckVersionParam.h"
#import "HBCheckVersionParser.h"


@implementation AppDelegate (NotificationCenter)

- (void)notifyApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self setupNotifiers];
    
    [self requestToCheckVersion];
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
//#warning 上线 AppStore 时需要修改BPushMode为BPushModeProduction 需要修改Apikey为自己的Apikey isDebug设置为NO
    
    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:@"2n9i5GGkGIQ89kCcgO2it8NB" pushMode:BPushModeDevelopment withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:NO];
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"从消息启动:%@",userInfo);
        [BPush handleNotification:userInfo];
    }
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

// 监听系统生命周期回调，以便将需要的事件传给SDK
- (void)setupNotifiers{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackgroundNotif:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidFinishLaunching:)
                                                 name:UIApplicationDidFinishLaunchingNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidBecomeActiveNotif:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillResignActiveNotif:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidReceiveMemoryWarning:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillTerminateNotif:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataWillBecomeUnavailableNotif:)
                                                 name:UIApplicationProtectedDataWillBecomeUnavailable
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataDidBecomeAvailableNotif:)
                                                 name:UIApplicationProtectedDataDidBecomeAvailable
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appLoginDidQuitoutNotif:)
                                                 name:Notification_LoginDismiss
                                               object:nil];
}

#pragma mark - notifiers

- (void)appDidEnterBackgroundNotif:(NSNotification*)notif
{
    
}

- (void)appWillEnterForeground:(NSNotification*)notif
{
    
}

- (void)appDidFinishLaunching:(NSNotification*)notif
{
    
}

- (void)appDidBecomeActiveNotif:(NSNotification*)notif
{
    
}

- (void)appWillResignActiveNotif:(NSNotification*)notif
{
    
}

- (void)appDidReceiveMemoryWarning:(NSNotification*)notif
{
    
}

- (void)appWillTerminateNotif:(NSNotification*)notif
{
    
}

- (void)appProtectedDataWillBecomeUnavailableNotif:(NSNotification*)notif
{
    
}

- (void)appProtectedDataDidBecomeAvailableNotif:(NSNotification*)notif
{
    
}

- (void)appLoginDidQuitoutNotif:(NSNotification*)notif
{
    [HBLoginManager didLoginOut];
}

#pragma mark - remote notify

// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    // 打印到日志 textView 中
    
    LLog(@"********** iOS7.0之后 background **********");
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else//杀死状态下，直接跳转到跳转页面。
    {
        //跳转
//        SkipViewController *skipCtr = [[SkipViewController alloc]init];
//        // 根视图是nav 用push 方式跳转
//        [_tabBarCtr.selectedViewController pushViewController:skipCtr animated:YES];
//        /*
//         // 根视图是普通的viewctr 用present跳转
//         [_tabBarCtr.selectedViewController presentViewController:skipCtr animated:YES completion:nil]; */
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
    LLog(@"backgroud : %@",userInfo);
    
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
    [application registerForRemoteNotifications];
    
    
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    LLog(@"Register use deviceToken :%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        
        LLog(@"***************%@\n%@",BPushRequestMethodBind,result);
        
        /*
         {
         "app_id" = 7513026;
         "channel_id" = 5416479843838988336;
         "request_id" = 88888888;
         "user_id" = 786327276078862094;
         }
         */
        
        [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"channel_id"] forKey:Key_YunChannelid];
        [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"user_id"] forKey:Key_YunUserid];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        if ([HBLoginManager sharedHBLoginManager].hasLogined)
        {
            [HBSetPushAccountManager requestToSetPushAccountWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
                
            }];
        }
        
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
//        if (result) {
//            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
//                if (result) {
//                    NSLog(@"设置tag成功");
//                }
//            }];
//        }
        
    }];
    
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    LLog(@"DeviceToken 获取失败，原因：%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // App 收到推送的通知
    [BPush handleNotification:userInfo];
    LLog(@"********** ios7.0之前 **********");
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else//杀死状态下，直接跳转到跳转页面。
    {
//        SkipViewController *skipCtr = [[SkipViewController alloc]init];
//        [_tabBarCtr.selectedViewController pushViewController:skipCtr animated:YES];
    }
    
    
    LLog(@"%@",userInfo);
    
}


- (void)requestToCheckVersion
{
    HBCheckVersionParam *param = [[HBCheckVersionParam alloc]init];
 
    HBCheckVersionParser *parser = [[HBCheckVersionParser alloc]init];
    [NetCenter postDataFromURL:Method_checkVersion params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code==0)
        {
            HBCheckVersionInfo *checkVersionInfo = (HBCheckVersionInfo *)myResult.result;
            if (checkVersionInfo)
            {
                self.checkVersionInfo = checkVersionInfo;
                if ([checkVersionInfo.updateStatus integerValue]==0)
                {
                    NSString *message = [NSString stringWithFormat:@"有最新版本v%@，前往更新",checkVersionInfo.appVersion];
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"前往" otherButtonTitles:@"忽略",nil];
                    alertView.tag = 14501;
                    [alertView show];
                }
                else
                {
                    NSString *message = [NSString stringWithFormat:@"有最新版本v%@，前往更新",checkVersionInfo.appVersion];
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"前往" otherButtonTitles:nil];
                    alertView.tag = 14502;
                    [alertView show];
                }
                
                
            }
        }
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark -
#pragma mark - alertViewDlegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==14501||alertView.tag==14502) {
        if (buttonIndex ==0)
        {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.checkVersionInfo.appUrl]];
        }

    }
}



@end
